package com.gxar.quick.ar.server.base.sdk;

import cn.hutool.crypto.digest.DigestUtil;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.gxar.common.exception.APIRuntimeException;
import com.gxar.quick.ar.server.base.model.ResultCodeEnum;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.common.utils.CollectionUtils;
import org.springframework.stereotype.Component;

import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URLEncoder;

/**
 * 百度翻译sdk
 * <a href="https://fanyi-api.baidu.com/doc/21">百度翻译文档地址</a>
 *
 * @author linsy
 * @version 1.0
 * @created 2024/1/2 15:46
 */
@Component
public class BaiduTranslateSDK {

    /**
     * 翻译url
     */
    private final static String TRANSLATE_URL = "https://api.fanyi.baidu.com/api/trans/vip/translate?q=%s&from=%s&to=%s&appid=%s&salt=%s&sign=%s";
    /**
     * APPID
     */
    private final static String APP_ID = "20240102001928384";
    /**
     * 密钥
     */
    private final static String SECRET = "u5e7taFrOjB24E_PtGfI";

    /**
     * 翻译
     *
     * @param fromLanguage 原语言
     * @param src          文字
     * @param toLanguage   目标语言
     * @return 结果
     */
    public String translate(String fromLanguage, String src, String toLanguage) {
        String salt = String.valueOf(System.currentTimeMillis());
        String sign = APP_ID + src + salt + SECRET;
        sign = DigestUtil.md5Hex(sign);
        String url = String.format(TRANSLATE_URL, encode(src), fromLanguage, toLanguage, APP_ID, salt, sign);
        HttpResponse response = HttpUtil.createGet(url).timeout(60000).execute();
        int status = response.getStatus();
        if (status == HttpURLConnection.HTTP_OK) {
            String body = response.body();
            if (StringUtils.isBlank(body)) {
                return src;
            }
            JSONObject jsonObject = JSON.parseObject(body);
            JSONArray jsonArray = jsonObject.getJSONArray("trans_result");
            if (CollectionUtils.isEmpty(jsonArray)) {
                Object errorCode = jsonObject.get("error_code");
                Object errorMsg = jsonObject.get("error_msg");
                if (errorCode != null && errorMsg != null) {
                    throw new APIRuntimeException(Integer.parseInt(errorCode.toString()), errorMsg.toString());
                } else {
                    throw new APIRuntimeException(ResultCodeEnum.TRANSLATE_FAIL);
                }
            } else {
                Object object = jsonArray.get(0);
                JSONObject successBody = JSON.parseObject(JSON.toJSONString(object));
                return String.valueOf(successBody.get("dst"));
            }
        } else {
            throw new APIRuntimeException(ResultCodeEnum.TRANSLATE_FAIL);
        }
    }

    /**
     * 自动语言转换成英语
     *
     * @param src 文字
     * @return 翻译结果
     */
    public String autoTranslateEn(String src) {
        return translate("auto", src, "en");
    }

    /**
     * 自动语言转换成中文
     *
     * @param src 文字
     * @return 翻译结果
     */
    public String autoTranslateZh(String src) {
        return translate("auto", src, "zh");
    }

    /**
     * 对输入的字符串进行URL编码, 即转换为%20这种形式
     *
     * @param input 原文
     * @return URL编码. 如果编码失败, 则返回原文
     */
    private static String encode(String input) {
        if (input == null) {
            return "";
        }

        try {
            return URLEncoder.encode(input, "utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        return input;
    }

}
